<template>
  <div class="department" v-loading="isLoading">
    <!-- 最外层的卡片 -->
    <el-card class="box-card">
      <!-- tabs选项卡 -->
      <el-tabs v-model="activeName">
        <el-tab-pane label="组织架构" name="first">
          <div class="content">
            <!-- 顶部公司名称 -->
            <treeTool :item="company"></treeTool>
            <!-- 顶部公司名称 end-->

            <hr />
            <!-- 组织tree结构-->
            <el-tree
              :data="departmentsTree"
              :props="defaultProps"
              node-key="id"
              default-expand-all
              :expand-on-click-node="false"
            >
              <template slot-scope="{ node, data }">
                <treeTool
                  @openEdit="openEdit"
                  @openAdd="openAdd"
                  @refreshParts="getDepartment"
                  :item="data"
                ></treeTool>
              </template>
            </el-tree>
            <!-- 组织tree结构end-->
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 新增子部门对话框 -->
    <addDialog
      ref="mydialog"
      @refreshParts="getDepartment"
      :currentPart="currentPart"
      :showDialog.sync="showDialog"
      :allDepart="departments"
    ></addDialog>
    <!-- 新增子部门对话框 -->
  </div>
</template>

<script>
import treeTool from './components/tree-tool.vue'
import addDialog from './components/addDialog.vue'
import { getDepartmentApi } from '../../api/department'
import tranTree from '../../utils/tranTree'
export default {
  data() {
    return {
      isLoading: false,
      activeName: 'first',
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      departments: [
        { name: '组织', manager: '管理员', children: [] },
        { name: '员工', manager: '管理员', children: [] },
        {
          name: '财务部',
          children: [
            {
              name: '财务核算部',
              manager: '管理员'
            }
          ]
        }
      ],
      departmentsTree: [],
      company: {
        name: '传智博客',
        manager: '负责人',
        isTop: true
      },
      showDialog: false,
      currentPart: {}
    }
  },
  components: {
    treeTool,
    addDialog
  },
  methods: {
    async getDepartment() {
      this.isLoading = true
      const res = await getDepartmentApi()
      this.departments = res.depts
      this.departmentsTree = tranTree(res.depts, '')
      this.company = { ...this.company, ...res.depts[0] }
      this.isLoading = false
    },
    openAdd(item) {
      this.showDialog = true
      this.currentPart = item
    },
    openEdit(item) {
      this.showDialog = true
      this.currentPart = item
      this.$refs.mydialog.queryDepartment(item.id)
    }
  },
  computed: {},
  created() {
    this.getDepartment()
  }
}
</script>

<style lang="scss" scoped>
.department {
  padding: 20px;
  .box-card {
    padding: 50px 40px 0;
    .el-tabs {
      .el-tab-pane {
        padding: 50px 60px 0;
      }
    }
  }
}
</style>